package com.ahwei.product.controller;


import com.ahwei.common.rest.base.PageVo;
import com.ahwei.common.rest.base.R;
import com.ahwei.common.rest.base.ResultCode;
import com.ahwei.common.rest.exception.ApplicationException;
import com.ahwei.common.rest.exception.ResourceNotFoundException;
import com.ahwei.product.api.dto.ProductDto;
import com.ahwei.product.convert.ProductConvert;
import com.ahwei.product.entity.Product;
import com.ahwei.product.service.ProductService;
import com.ahwei.product.vo.ProductQueryVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ahwei
 * @since 2022-05-25
 */
@RestController
@RequestMapping("/api/product")
public class ProductController {
    @Resource
    private ProductService productService;

    /**
     * 分页查询
     *
     * @param productQueryVo 筛选条件
     * @param page           当前页数
     * @param limit          每页条数
     * @return 查询结果
     * <p>
     * //支持校验角色，角色不用加上“ROLE_”
     * @PreAuthorize("hasRole('admin')") //角色中需要加上“ROLE_”
     * @Secured({"ROLE_admin"})
     * @PreAuthorize("@pms.hasPermission('product.list1')")
     */
    @Operation(summary = "分页查询符合条件的信息", description = "按条件查询数据", parameters = {
            @Parameter(name = "page", description = "当前页数", in = ParameterIn.QUERY, schema = @Schema(implementation = Long.class)),
            @Parameter(name = "limit", description = "每页条数", in = ParameterIn.QUERY, schema = @Schema(implementation = Long.class)),
            @Parameter(name = "productQueryVo", description = "查询条件", in = ParameterIn.QUERY, schema = @Schema(implementation = ProductQueryVo.class))})
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "操作成功", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = R.class))}), @ApiResponse(responseCode = "404", description = "未找到相关信息", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = R.class))})})
    @ResponseStatus(HttpStatus.OK)
    @GetMapping("/{page}/{limit}")
    public R<PageVo<Product>> listPage(@PathVariable Long page,
                                       @PathVariable Long limit,
                                       ProductQueryVo productQueryVo) {
        //传入分页参数
        IPage<Product> pageParam = new Page<>(page, limit);

        PageVo<Product> productPageVo = productService.listPage(pageParam, productQueryVo);

        List<ProductDto> productDtoList = ProductConvert.INSTANCE.entityList2dtoList(productPageVo.getDataList());
        // 如果没有数据，就抛异常没有找到资源
        if (productPageVo.getDataList().size() == 0) {
            throw new ResourceNotFoundException("未找到相关信息！");
        }
        return R.ok(productPageVo);
    }

    @Operation(summary = "扣减库存", description = "扣减库存", parameters = {
            @Parameter(name = "productId", description = "商品ID", in = ParameterIn.QUERY, schema = @Schema(implementation = Long.class)),
            @Parameter(name = "quantity", description = "下单数量", in = ParameterIn.QUERY, schema = @Schema(implementation = Integer.class))})
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "操作成功", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = R.class))}), @ApiResponse(responseCode = "404", description = "未找到相关信息", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = R.class))})})
    @PostMapping("/reduceInventory")
    public void reduceInventory(Long productId, Integer quantity) {
        productService.reduceInventory(productId, quantity);
    }








    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Operation(summary = "通过ID查询单条数据", description = "通过ID查询单条数据", parameters = {
            @Parameter(name = "id", description = "唯一标识", in = ParameterIn.QUERY, schema = @Schema(implementation = Integer.class))})
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "操作成功", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = R.class))}), @ApiResponse(responseCode = "404", description = "未找到相关信息",content = {@Content(mediaType = "application/json", schema = @Schema(implementation = R.class))})})
    @GetMapping("/{id}")
    public R<ProductDto> getById(@PathVariable("id") Long id, HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        System.out.println("authorization=" + authorization);

        Product product = productService.getById(id);
        // 如果没有数据，就抛异常没有找到资源
        if (null != product) {
            ProductDto productDto = ProductConvert.INSTANCE.entity2dto(product);
            return R.ok(productDto);
        }

        throw new ResourceNotFoundException("未找到相关信息！");
    }
    /**
     * 新增数据
     *
     * @return 新增结果
     */
    @PostMapping()
    @Operation(summary = "新增数据", description = "新增数据", parameters = {
            @Parameter(name = "product", description = "封装信息", in = ParameterIn.QUERY, schema = @Schema(implementation = Product.class))})
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "操作成功", content = {@Content(mediaType = "application/json",schema = @Schema(implementation = R.class))}),})
    @ResponseStatus(HttpStatus.CREATED)
    public R<Object> save(@Valid @RequestBody ProductDto productDto) {
        // 将ProductDto转为Product
        Product product = ProductConvert.INSTANCE.dto2entity(productDto);
        boolean save = productService.save(product);
        if (save){
            return R.ok(ResultCode.SUCCESS,"保存成功！");
        }
        throw new ApplicationException("保存失败！");
    }

    /**
     * 更新数据
     *
     * @return 更新结果
     */
    @PutMapping()
    @Operation(summary = "更新数据", description = "更新数据", parameters = {
            @Parameter(name = "product", description = "更新信息", in = ParameterIn.QUERY, schema = @Schema(implementation = Product.class))})
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "操作成功", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = R.class))}),})
    @ResponseStatus(HttpStatus.OK)
    public R<Object> update(@Valid @RequestBody ProductDto productDto) {
        //将ProductDto转为Product
        Product product = ProductConvert.INSTANCE.dto2entity(productDto);

        boolean update = productService.updateById(product);
        if (update){
            return R.ok(ResultCode.SUCCESS,"更新成功！");
        }
        throw new ApplicationException("更新失败！");
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除数据", description = "删除数据", parameters = {
            @Parameter(name = "id", description = "唯一标识", in = ParameterIn.QUERY, schema = @Schema(implementation = List.class))})
    public R<Object> remove(@PathVariable("id") List<Long> id) {
        boolean remove = productService.removeByIds(id);
        if (remove) {
            return R.ok(ResultCode.SUCCESS,"删除成功！");
        }
        throw new ApplicationException("删除失败！");
    }
}

